"""
@Author    : ghenyar
@Time      : 2025/8/27 11:27
@File      : main
@Desc      : 
"""
import asyncio
from contextlib import asynccontextmanager

import uvicorn
from fastapi import FastAPI, WebSocket, WebSocketDisconnect

from app.common.scheduler_timer import start_scheduler, stop_scheduler

from app.libs.wsocket import wsocket

from app.common.commFunc import get_file
from app.utils.redisCache import RedisCache

from app.admin import app_admin


@asynccontextmanager
async def lifespan(_app: FastAPI):
    # 项目启动时
    print(prod_start)
    # 启动定时任务调度器
    await start_scheduler()
    # 链接redis
    await RedisCache.init_redis()
    yield
    # 项目停止
    print(prod_stop)
    # 停止定时任务调度器
    await stop_scheduler()
    # 断开redis链接
    await RedisCache.close()


app = FastAPI(lifespan=lifespan)
# 加载静态文件
app.add_route("/file/{file_name}", get_file, methods=["GET"])  # 文件访问
app.mount("/admin", app_admin)  # 后台应用


@app.websocket("/ws")
async def websocket_serve(websocket: WebSocket):
    """
    websocket通讯
    :param websocket:
    :return:
    """
    try:
        await wsocket.connect(websocket)
        # 并行运行心跳机制和消息发送
        await asyncio.gather(
            wsocket.heartbeat(websocket),
            wsocket.send(websocket)
        )
    except WebSocketDisconnect:
        await wsocket.disconnect(websocket)


prod_start = """
██████╗ ██████╗  ██████╗     ███████╗████████╗ █████╗ ████████╗███████╗██████╗ 
██╔══██╗██╔══██╗██╔═══██╗    ██╔════╝╚══██╔══╝██╔══██╗╚══██╔══╝██╔════╝██╔══██╗
██████╔╝██████╔╝██║   ██║    ███████╗   ██║   ███████║   ██║   █████╗  ██║  ██║
██╔═══╝ ██╔══██╗██║   ██║    ╚════██║   ██║   ██╔══██║   ██║   ██╔══╝  ██║  ██║
██║     ██║  ██║╚██████╔╝    ███████║   ██║   ██║  ██║   ██║   ███████╗██████╔╝
╚═╝     ╚═╝  ╚═╝ ╚═════╝     ╚══════╝   ╚═╝   ╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═════╝ 
"""
prod_stop = """
██████╗ ██████╗  ██████╗     ███████╗████████╗ ██████╗ ██████╗ 
██╔══██╗██╔══██╗██╔═══██╗    ██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗
██████╔╝██████╔╝██║   ██║    ███████╗   ██║   ██║   ██║██████╔╝
██╔═══╝ ██╔══██╗██║   ██║    ╚════██║   ██║   ██║   ██║██╔═══╝ 
██║     ██║  ██║╚██████╔╝    ███████║   ██║   ╚██████╔╝██║     
╚═╝     ╚═╝  ╚═╝ ╚═════╝     ╚══════╝   ╚═╝    ╚═════╝ ╚═╝     
"""

if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8094, reload=True)
